<template>
  <div class="prdp-outer">
    <div class="prdp-main">
      <!-- 头部标题栏 -->
      <div class="prdp-title-bar">
        <h2>历史记录</h2>
      </div>
      <!-- 搜索栏 -->
      <div class="prdp-search-container">
        <el-form :inline="true" :model="searchForm" class="aprd-search-form">
          <el-form-item label="输入编号：">
            <el-input v-model="searchForm.inputNum" placeholder="输入" style="width:120px" />
          </el-form-item>
          <el-form-item label="打滑编号：">
            <el-input v-model="searchForm.slipNum" placeholder="输入" style="width:120px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </el-form-item>
          <el-form-item label="时间范围：">
            <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="-" start-placeholder="开始时间"
              end-placeholder="结束时间" style="width:220px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary">获取处理时间</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success">导出</el-button>
          </el-form-item>
          <el-form-item>
            <el-button>组合查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- Tabs + 表格 -->
      <div class="prdp-table-container">
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="打滑报警" name="slip">
            <el-table :data="tableDataSlip" border style="width: 100%"
              :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 'bold', textAlign: 'center' }"
              :cell-style="{ textAlign: 'center', color: '#333' }" @row-click="handleRowClick">
              <!-- 保持原有字段 -->
              <el-table-column prop="time" label="时间" />
              <el-table-column prop="slipName" label="打滑编号" />
              <el-table-column prop="slipSteelNum" label="打滑带钢编号" />
              <el-table-column prop="steelGrade" label="钢牌号" />
              <el-table-column prop="thick" label="带钢厚度[mm]" />
              <el-table-column prop="width" label="带钢宽度[mm]" />
              <el-table-column prop="speed" label="速度实测值[m/min]" />
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="挠曲度报警" name="deflectionAlarm">
            <el-table :data="tableDataDeflectionAlarm" border style="width: 100%"
              :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 'bold', textAlign: 'center' }"
              :cell-style="{ textAlign: 'center', color: '#333' }">
              <el-table-column prop="time" label="时间" />
              <el-table-column prop="slipName" label="打滑编号" />
              <el-table-column prop="slipSteelNum" label="打滑带钢编号" />
              <el-table-column prop="steelGrade" label="钢牌号" />
              <el-table-column prop="thick" label="带钢厚度[mm]" />
              <el-table-column prop="width" label="带钢宽度[mm]" />
              <el-table-column prop="speed" label="速度实测值[m/min]" />
              <el-table-column prop="freq" label="频率" />
              <el-table-column prop="deflection" label="挠曲度" />
              <el-table-column prop="deflectionThreshold" label="挠曲度阈值" />
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="挠曲度趋势" name="deflectionTrend">
            <div class="trend-grid">
              <div class="trend-card" v-for="(name, idx) in trendCards" :key="'tc-' + idx">
                <div class="trend-title">{{ name }}</div>
                <div class="trend-mini" :id="'trend-mini-' + idx"></div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
        <!-- 分页 -->
        <div class="prdp-pagination">
          <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 30, 50, 100]" :total="pagination.total" background
            layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <!-- 打滑详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="打滑详情" width="90%" :close-on-click-modal="false"
      :close-on-press-escape="false" class="slip-detail-dialog">
      <div class="slip-detail-content">
        <!-- 头部信息 -->
        <div class="slip-header">
          <div class="coil-number">
            <span class="label">打滑带钢卷号:</span>
            <span class="value">{{ selectedRow?.slipSteelNum || '-' }}</span>
          </div>
          <div class="slip-legend">
            <span class="label">炉区打滑标志:</span>
            <span class="value">1-单支辊打滑 2-转矩波动较大 3-炉区多个段打滑</span>
          </div>
        </div>

        <!-- 数据表格 -->
        <div class="data-table-section">
          <el-table :data="detailTableData" border style="width: 100%" size="small">
            <el-table-column prop="time" label="时间" min-width="180" />
            <el-table-column prop="rollNumber" label="辊号" min-width="200" />
            <el-table-column prop="slipCoilNumber" label="打滑带钢卷号" min-width="180" />
            <el-table-column prop="tensionZone" label="炉辊所在张力段" min-width="150" />
            <el-table-column prop="steelGrade" label="钢牌号" min-width="120" />
            <el-table-column prop="thickness" label="带钢厚度" min-width="100" />
            <el-table-column prop="width" label="带钢宽度" min-width="100" />
            <el-table-column prop="actualSpeed" label="速度实际值[m/min]" min-width="150" />
            <el-table-column prop="sectionSlipMark" label="段打滑标志" min-width="100" />
            <el-table-column prop="furnaceSlipMark" label="炉区打滑标志" min-width="120" />
          </el-table>
        </div>

        <!-- 图表区域 -->
        <div class="charts-section">
          <div class="chart-container">
            <div class="chart-title">速度</div>
            <div class="chart" ref="speedChartRef"></div>
          </div>
          <div class="chart-container">
            <div class="chart-title">转矩(N·M)</div>
            <div class="chart" ref="torqueChartRef"></div>
          </div>
          <div class="chart-container">
            <div class="chart-title">张力实际值(N)</div>
            <div class="chart" ref="tensionChartRef"></div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, onUnmounted, watch, onMounted } from 'vue';
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import { GridComponent, TitleComponent, TooltipComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { ElMessage } from 'element-plus';
import { zlgdhApi } from '/@/api/zlgdh/index';

echarts.use([LineChart, GridComponent, TitleComponent, TooltipComponent, CanvasRenderer]);

const searchForm = reactive({
  inputNum: '',
  slipNum: '',
  dateRange: [],
});

const tableDataSlip = ref([]);

const tableDataDeflectionAlarm = ref([]);
const tableDataDeflectionTrend = ref([]);

// 当前激活tab
const activeTab = ref('slip');

// 挠曲度趋势页：小图网格
const trendCards = ref([
  'F-Cooling Guide Roll 1', 'F-Cooling Guide Roll 2', 'F-Cooling Guide Roll 3', 'F-Cooling Guide Roll 4',
  'F-Cooling Guide Roll 5', 'F-Cooling Guide Roll 6', 'F-Cooling Guide Roll 7', 'F-Cooling Guide Roll 8',
  'F-Cooling Guide Roll 9', 'F-Cooling Guide Roll 10', 'R-Cooling Guide Roll 1', 'R-Cooling Guide Roll 2',
  'R-Cooling Guide Roll 3', 'R-Cooling Guide Roll 4', 'R-Cooling Guide Roll 5', 'R-Cooling Guide Roll 6',
]);
const trendChartInstances: echarts.ECharts[] = [];

// 弹窗相关数据
const dialogVisible = ref(false);
const selectedRow = ref<any>(null);
const detailTableData = ref<any[]>([]);

// 图表引用
const speedChartRef = ref<HTMLElement>();
const torqueChartRef = ref<HTMLElement>();
const tensionChartRef = ref<HTMLElement>();

// 图表实例
let speedChart: echarts.ECharts | null = null;
let torqueChart: echarts.ECharts | null = null;
let tensionChart: echarts.ECharts | null = null;

// 处理行点击事件
const handleRowClick = (row: any) => {
  selectedRow.value = row;
  dialogVisible.value = true;

  // 模拟详情数据（后续可替换为接口调用）
  detailTableData.value = [
    {
      time: row.time,
      rollNumber: row.slipName,
      slipCoilNumber: row.slipSteelNum,
      tensionZone: getTensionZone(row.slipName),
      steelGrade: row.steelGrade,
      thickness: row.thick,
      width: row.width,
      actualSpeed: row.speed,
      sectionSlipMark: 0,
      furnaceSlipMark: 2
    }
  ];

  // 初始化图表
  nextTick(() => {
    initDetailCharts();
  });
};

// 获取张力段名称
const getTensionZone = (rollName: string): string => {
  if (rollName.includes('Heating1')) return '加热段1';
  if (rollName.includes('Heating2')) return '加热段2';
  if (rollName.includes('Overaging')) return '过时效段';
  if (rollName.includes('Cooling')) return '冷却段';
  if (rollName.includes('Entry')) return '入口段';
  return '未知段';
};

// 初始化详情图表
const initDetailCharts = () => {
  // 速度图表
  if (speedChartRef.value && !speedChart) {
    speedChart = echarts.init(speedChartRef.value);
  }
  if (speedChart) {
    const speedOption = {
      grid: { left: 40, right: 20, top: 30, bottom: 30 },
      legend: {
        data: ['实际值', '设定值', '带钢速度', '速度差(实际速度-设定速度)'],
        textStyle: { fontSize: 12 }
      },
      xAxis: {
        type: 'category',
        data: Array.from({ length: 20 }, (_, i) => i),
        axisLine: { lineStyle: { color: '#7fb4ff' } }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 5,
        axisLine: { lineStyle: { color: '#7fb4ff' } }
      },
      series: [
        { name: '实际值', type: 'line', data: Array.from({ length: 20 }, () => 4), lineStyle: { color: '#409eff' } },
        { name: '设定值', type: 'line', data: Array.from({ length: 20 }, () => 4), lineStyle: { color: '#ffa500' } },
        { name: '带钢速度', type: 'line', data: Array.from({ length: 20 }, () => 4), lineStyle: { color: '#ff0000' } },
        { name: '速度差(实际速度-设定速度)', type: 'line', data: Array.from({ length: 20 }, () => 0), lineStyle: { color: '#00ff00' } }
      ]
    };
    speedChart.setOption(speedOption);
  }

  // 转矩图表
  if (torqueChartRef.value && !torqueChart) {
    torqueChart = echarts.init(torqueChartRef.value);
  }
  if (torqueChart) {
    const torqueOption = {
      grid: { left: 40, right: 20, top: 30, bottom: 30 },
      xAxis: {
        type: 'category',
        data: Array.from({ length: 20 }, (_, i) => i),
        axisLine: { lineStyle: { color: '#7fb4ff' } }
      },
      yAxis: {
        type: 'value',
        min: -30,
        max: 30,
        axisLine: { lineStyle: { color: '#7fb4ff' } }
      },
      series: [
        { type: 'line', data: Array.from({ length: 20 }, () => Math.random() * 10 - 5), lineStyle: { color: '#409eff' } }
      ]
    };
    torqueChart.setOption(torqueOption);
  }

  // 张力图表
  if (tensionChartRef.value && !tensionChart) {
    tensionChart = echarts.init(tensionChartRef.value);
  }
  if (tensionChart) {
    const tensionOption = {
      grid: { left: 40, right: 20, top: 30, bottom: 30 },
      xAxis: {
        type: 'category',
        data: Array.from({ length: 20 }, (_, i) => i),
        axisLine: { lineStyle: { color: '#7fb4ff' } }
      },
      yAxis: {
        type: 'value',
        min: -100,
        max: 100,
        axisLine: { lineStyle: { color: '#7fb4ff' } }
      },
      series: [
        { type: 'line', data: Array.from({ length: 20 }, () => Math.random() > 0.5 ? 50 : -50), lineStyle: { color: '#409eff' } }
      ]
    };
    tensionChart.setOption(tensionOption);
  }
};

// 监听弹窗关闭，清理图表
watch(dialogVisible, (visible) => {
  if (!visible) {
    if (speedChart) speedChart.dispose();
    if (torqueChart) torqueChart.dispose();
    if (tensionChart) tensionChart.dispose();
    speedChart = null;
    torqueChart = null;
    tensionChart = null;
  }
});

function initTrendCharts() {
  disposeTrendCharts();
  nextTick(() => {
    trendCards.value.forEach((_, idx) => {
      const el = document.getElementById(`trend-mini-${idx}`);
      if (!el) return;
      const chart = echarts.init(el);
      const option = {
        animation: false,
        grid: { left: 12, right: 12, top: 10, bottom: 16 },
        xAxis: {
          type: 'category',
          data: Array.from({ length: 30 }, (_, i) => i),
          axisLine: { show: true, lineStyle: { color: '#7fb4ff', width: 1 } },
          axisTick: { show: false },
          axisLabel: { show: false },
          splitLine: { show: false },
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 1,
          axisLine: { show: true, lineStyle: { color: '#7fb4ff', width: 1 } },
          axisTick: { show: false },
          axisLabel: { show: false },
          splitLine: { show: true, lineStyle: { color: 'rgba(127,180,255,0.25)', type: 'dashed' } },
        },
        series: [
          {
            type: 'line',
            data: Array.from({ length: 30 }, () => 0),
            showSymbol: false,
            lineStyle: { color: '#ffd400', width: 3, shadowBlur: 8, shadowColor: 'rgba(255,212,0,0.65)' },
            areaStyle: { color: 'rgba(255,212,0,0.15)' },
          },
        ],
        tooltip: { show: true, trigger: 'axis', axisPointer: { type: 'line', lineStyle: { color: '#ffd400' } } },
      } as any;
      chart.setOption(option);
      trendChartInstances.push(chart);
    });
  });
}

function disposeTrendCharts() {
  while (trendChartInstances.length) {
    const c = trendChartInstances.pop();
    if (c) c.dispose();
  }
}

watch(activeTab, (val) => {
  if (val === 'deflectionTrend') initTrendCharts();
  else disposeTrendCharts();
});

onUnmounted(() => disposeTrendCharts());

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 15,
});

const handleSearch = () => {
  fetchSlipTableData();
};
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  fetchSlipTableData();
};
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  fetchSlipTableData();
};

function confirmRow(index: number) {
  (tableDataSlip as any).value[index].confirmed = true;
}

// 获取打滑报警表数据（复用 ZLGDH1630.vue 的接口）
const fetchSlipTableData = async () => {
  try {
    const params: any = {
      pageIndex: String(pagination.currentPage),
      pageSize: String(pagination.pageSize),
    };
    const response = await zlgdhApi.getData(params);
    const responseData = (response as any).data;
    if (responseData && responseData.data && Array.isArray(responseData.data.records)) {
      (tableDataSlip as any).value = responseData.data.records.map((item: any, idx: number) => ({
        // 保留原有展示字段（若接口无对应值则占位）
        time: item.time ?? item.modifyTime ?? '-',
        slipName: item.slipName ?? item.rollID ?? '-',
        slipSteelNum: item.slipSteelNum ?? item.coilID ?? '-',
        steelGrade: item.steelGrade ?? '-',
        thick: item.thick ?? item.enThick ?? '-',
        width: item.width ?? item.enWidth ?? '-',
        speed: parseFloat(item.actAvgSpd).toFixed(0) ?? '-',
        // 追加接口字段
        modifyTime: item.modifyTime ?? '-',
        rollID: item.rollID ?? '-',
        slipReason: item.slipReason ?? '-',
        // 本地状态
        confirmed: false,
        _idx: idx,
        _raw: item,
      }));
      pagination.total = Number(responseData.data.total || responseData.data.records.length || 0);
      if (responseData.msg) ElMessage.success(responseData.msg);
    } else {
      (tableDataSlip as any).value = [];
      pagination.total = 0;
      ElMessage.info(responseData?.msg || '未查询到数据');
    }
  } catch (error: any) {
    (tableDataSlip as any).value = [];
    pagination.total = 0;
    const errorMessage = error?.response?.data?.msg || error?.message || '获取数据失败';
    ElMessage.error(errorMessage);
  }
};

onMounted(() => {
  if (activeTab.value === 'slip') fetchSlipTableData();
});

watch(activeTab, (val) => {
  if (val === 'slip') fetchSlipTableData();
});
</script>

<style scoped>
.prdp-outer {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(to top, #eaf1fb 0%, #2c69e8 100%);
  overflow: hidden;
}

.prdp-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  padding: 20px;
}

.prdp-table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.el-table {
  flex: 1;
  height: 100% !important;
  min-height: 0;
}

.prdp-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.prdp-title-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.prdp-title-bar h2 {
  margin: 0;
  color: #333;
}

.prdp-status-indicators {
  display: flex;
  gap: 20px;
}

.prdp-status-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.prdp-status-text {
  color: #333;
  font-size: 14px;
}

.prdp-status-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: #67c23a;
  display: inline-block;
}

.prdp-search-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.prdp-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 等级指示器样式 */
.prdp-grade-indicator {
  display: flex;
  justify-content: center;
}

.prdp-grade-a {
  color: #67c23a;
  font-weight: bold;
}

.prdp-grade-b {
  color: #409eff;
  font-weight: bold;
}

.prdp-grade-c {
  color: #e6a23c;
  font-weight: bold;
}

.prdp-grade-d {
  color: #f56c6c;
  font-weight: bold;
}

.prdp-rate-indicator {
  text-align: center;
}

/* 趋势格子样式，保持与全局主题一致 */
.trend-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 18px 24px;
  padding: 6px 4px 0 4px;
}

.trend-card {
  background: transparent;
  border: none;
}

.trend-title {
  color: #2f4a73;
  font-size: 13px;
  font-weight: 600;
  margin-bottom: 8px;
}

.trend-mini {
  width: 100%;
  height: 140px;
  background: #ffffff;
  border: 1px solid #c9dbf5;
  border-radius: 4px;
}

/* 弹窗样式 */
.slip-detail-dialog {
  .el-dialog__body {
    padding: 20px;
  }
}

.slip-detail-content {
  .slip-header {
    margin-bottom: 20px;
    padding: 15px;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    border-radius: 8px;

    .coil-number {
      margin-bottom: 10px;

      .label {
        font-weight: bold;
        color: #2c3e50;
        margin-right: 10px;
      }

      .value {
        color: #e74c3c;
        font-size: 18px;
        font-weight: bold;
      }
    }

    .slip-legend {
      .label {
        font-weight: bold;
        color: #2c3e50;
        margin-right: 10px;
      }

      .value {
        color: #7f8c8d;
        font-size: 14px;
      }
    }
  }

  .data-table-section {
    margin-bottom: 20px;

    .el-table {
      .el-table__header {
        background: #34495e;

        th {
          background: #34495e !important;
          color: white !important;
          font-weight: bold;
        }
      }
    }
  }

  .charts-section {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;

    .chart-container {
      background: #ffffff;
      border: 1px solid #e1e8ed;
      border-radius: 8px;
      padding: 15px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

      .chart-title {
        font-size: 16px;
        font-weight: bold;
        color: #2c3e50;
        margin-bottom: 15px;
        text-align: center;
        padding-bottom: 10px;
        border-bottom: 2px solid #3498db;
      }

      .chart {
        width: 100%;
        height: 300px;
      }
    }
  }
}
</style>
